import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { cloneDeep } from "lodash"
import { allAsyncRoutes, anyRoute, staticRoutes } from '@/router/routes'


//封装过滤用户要显示的异步路由函数
function fillterAsyncRoutes(allAsyncRoutes, getRouterNameList) {
  return allAsyncRoutes.filter(item => {
    //此处只能过滤一级路由,所以我们要使用深拷贝来对所有的路由进行深层次的拷贝
    if (getRouterNameList.indexOf(item.name) !== -1) {
      if (item.children && item.children.length > 0) {
        item.children = fillterAsyncRoutes(item.children, getRouterNameList)
      }
      return true
    }
  })
}

//封装将过滤后的异步路由动态添加至静态路由中的函数
// function addRoutes(routes) {
//   (routes)
// }


const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    routes: [],
    roles: [],
    buttons: [],
  }
}

const state = getDefaultState()


const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  async getInfo({ commit, state }) {

    try {
      let result = await getInfo()
      const { name, avatar, routes, buttons, roles } = result.data
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      commit('SET_ROUTES', routes)
      commit('SET_ROLES', roles)
      commit('SET_BUTTONS', buttons)
      let asyncRoutes = fillterAsyncRoutes(cloneDeep(allAsyncRoutes), routes)
      // addRoutes(asyncRoutes.concat(anyRoute))
      //将过滤后的路由注册进路由
      router.addRoutes(asyncRoutes.concat(anyRoute))
      router.options.routes = staticRoutes.concat(asyncRoutes.concat(anyRoute))
      return 'ok'
    } catch (error) {
      // console.log('获取用户信息失败', error)
      return Promise.reject(new Error('failed'))
    }
    // return new Promise((resolve, reject) => {
    //   getInfo(state.token).then(response => {
    //     console.log(response)
    //     const { data } = response

    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }

    //     const { name, avatar } = data

    //     commit('SET_NAME', name)
    //     commit('SET_AVATAR', avatar)
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // user logout
  async logout() {
    try {
      await logout()
      removeToken() // must remove  token  first
      resetRouter()
    } catch (error) {
      Message.error('退出登录失败')
    }
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

